package com.song.invoicing.service.impl;

import com.song.invoicing.exception.LoginException;
import com.song.invoicing.exception.RegisterException;
import com.song.invoicing.mapper.UserMapper;
import com.song.invoicing.pojo.dao.User;
import com.song.invoicing.pojo.dto.UserLoginDTO;
import com.song.invoicing.pojo.dto.UserRegisterDTO;
import com.song.invoicing.pojo.UserAuthorization;
import com.song.invoicing.pojo.vo.UserVO;
import com.song.invoicing.properties.JwtProperties;
import com.song.invoicing.service.UserService;
import com.song.invoicing.utils.BaseContext;
import com.song.invoicing.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final JwtProperties jwtProperties;
    @Override
    public UserAuthorization login(UserLoginDTO userLoginDTO)  {
        //1.获取用户名
        String username = userLoginDTO.getUsername();
        //2.获取密码，需要将密码进行md5加密然后及逆行数据库查询比对
        String password = userLoginDTO.getPassword();
        //加密
        String encryptPassword =  DigestUtils.md5DigestAsHex(password.getBytes());
        //3.查询登录用户是否存在
        Long userId = userMapper.login(username,encryptPassword);
         if(userId==null){
             //3.1 userId==null，登陆失败
             throw new LoginException("用户名或者密码错误");
         }
         //3.2登陆成功，生成token
         Map<String,Object> claims = new HashMap<>();
         claims.put("userId",userId);
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        return new UserAuthorization(token);
    }

    @Override
    public void register(UserRegisterDTO userRegisterDTO) {
        //1.根据用户名进行账号查询
       int count = userMapper.selectByUsername(userRegisterDTO.getUsername());
       //2.判断用户是否已经存在
        if(count>0){
            //2.1存在抛出异常
            throw new RegisterException("用户名已经存在");
        }
        //2.2不存在
        //3.进行两次密码比对
        if(!isEquals(userRegisterDTO.getPassword(),userRegisterDTO.getConfirmPassword())){
            //3.1不相等
            throw new RegisterException("两次密码不相同");
        }
        //3.2进行数据库保存
        try {
            User user = new User();
            user.setUsername(userRegisterDTO.getUsername());
            //md5加密
            user.setPassword(DigestUtils.md5DigestAsHex(userRegisterDTO.getPassword().getBytes()));
            user.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            user.setUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            userMapper.saveUserInfo(user);
        } catch (Exception e) {
            throw new RegisterException("注册失败，原因:"+e.getMessage());
        }
    }

    @Override
    public UserVO getUserInfo() {
        //1.从threadLocal中获取userId
        Long userId = BaseContext.getCurrentId();
        //2.查询用户信息
        return userMapper.getUserInfo(userId);
    }

    private boolean isEquals(String password, String confirmPassword) {
        return password != null && password.equals(confirmPassword);
    }
}
